// pages/order/order.js
const app = getApp()
const Host = require('../../config').Host
Page({

    /**
     * 页面的初始数据
     */
    data: {
        hasAddress: true,
        title:'请选择',
        title2: '请选择',
        couponShow:false,
        // chooseCouponIndex:-1,
        coupon_deduction:0,
        intergrationShow:false,
        chooseIntergrartionIndex: -1,
        intergration_deduction: 0,
      coupon: [],
        intergration: [],
        submission: {},
        textValue: "",
        textValueLength: 0,
        all_price: '',
        total_price: '',
        freight:0,
        drawid:0,
        canusejifen:0.00
    },
    gettextValue: function (e) {
        var value = e.detail.value;
        var arr = value.split("");
        this.setData({
            textValue: value,
            textValueLength: arr.length,
        })

    },
    couponShow:function(){
      var that = this;
      if (that.data.coupon.length > 0) {
        if (that.data.couponShow) {
          that.setData({
            couponShow: false,
          })
        } else {
          that.setData({
            couponShow: true,
          })
        }
      }
    },
    intergrationShow: function () {
      var that=this;
      var openid = wx.getStorageSync('openid');
      var totalprice = that.data.total_price;
      //获取可用积分
      wx.request({
        url: Host + 'Order/choosejifen',
        data: { openid, totalprice },
        method: 'post',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function (res) {
          if (res.data.code == 200) {
            that.setData({
              intergration: res.data.intergration
            })
            if (that.data.intergration.length > 0) {
              if (that.data.intergrationShow) {
                that.setData({
                  intergrationShow: false,
                })
              } else {
                that.setData({
                  intergrationShow: true,
                })
              }
            }
            //console.log(res.data.intergration)
          }
        },
      })
    },
    bindPickerChange:function(e){
        //console.log(e.detail.value)
        var that=this;
        var coupon = that.data.coupon; 
        var title = coupon[e.detail.value].title;
        var deduction = coupon[e.detail.value].value;
        var id = coupon[e.detail.value].id;
        //console.log(id)
        that.setData({
            couponShow:false,
            title:title,
            coupon_deduction: deduction,
            drawid: id,
        })
        that.cac();
    },
    chooseIntergration:function (e) {
        var that = this;
        var intergration = that.data.intergration;
        var index = e.currentTarget.id;
        var title = intergration[index].title;
        var deduction = intergration[index].value;
        var canusejifen = intergration[index].canusejifen;
        that.setData({
            chooseIntergrationIndex: index,
            intergrationShow: false,
            title2: title,
            intergration_deduction: deduction,
            canusejifen: canusejifen
        })
        that.cac();
    },
    cac:function(){
        var that = this;
        var submission = that.data.submission;
        var arr1 = [];
        submission.goodsList.forEach(item => {
            arr1.push(item.price * item.num);
        })
        //console.log(arr1);
        var all_price = 0;
        arr1.forEach(item => {
            all_price += parseFloat(item);
        })
      var total_price = all_price + that.data.freight - parseInt(that.data.coupon_deduction) - parseFloat(that.data.intergration_deduction);
        if (total_price<0){
            total_price=0;
        }
        //console.log(all_price, total_price)
        that.setData({
            all_price: all_price.toFixed(2),
            total_price: total_price.toFixed(2),
        })
    },
    //提交订单
    subOrder:function(){
      var that=this;
      var drawid = that.data.drawid;
      var canusejifen = that.data.canusejifen;
      var openid = wx.getStorageSync('openid');
      var order = wx.getStorageSync('order');
      var address_id = wx.getStorageSync('addressId');
      var bz = that.data.textValue;

      if (!address_id) {
        wx.showToast({
          title: '请填写收货地址！',
          icon: 'none',//  loading/success/none        
          duration: 2000
        })
        return false;
      }

      //下单
      wx.request({
        url: Host + 'Order/place_goodsorder',
        data: { order: JSON.stringify(order), openid, drawid, canusejifen, address_id,bz},
        method: 'post',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function (res) {
          if (res.data.code != 200) {
            wx.showToast({
              title: res.data.errmsg,
              icon: 'none',//  loading/success/none        
              duration: 2000
            })
          } else if (res.data.code == 200) {
            if (res.data.money <= 0) {
              wx.showToast({
                title: '下单成功',
                icon: 'none',//  loading/success/none        
                duration: 2000
              })
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/submission_should_get/submission_should_get?id=2'
                })
              }, 500);
            } else {
              var out_trade_no = res.data.ordernum
              wx.request({
                url: Host + 'Pay/order_zhifu',
                data: { out_trade_no, openid },
                method: 'get',
                success: function (res) {
                  if (res.data.code==400) {
                    wx.showToast({
                      title: res.data.errmsg,
                      icon: 'none',//  loading/success/none        
                      duration: 2000
                    })
                  } else {
                    wx.requestPayment({
                      'appId': res.data.appId,
                      'timeStamp': res.data.timeStamp,
                      'nonceStr': res.data.nonceStr,
                      'package': res.data.package,
                      'signType': res.data.signType,
                      'paySign': res.data.paySign,
                      'success': function (res) {
                        //console.log(res);
                        wx.redirectTo({
                          url: '/pages/submission_should_get/submission_should_get?id=2'
                        })
                      },
                      'fail': function (res) {
                        //console.log(res);
                      }
                    })
                  }
                }
              })

            }
          }
        }
      })
      
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that=this;
       
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      var that=this;
      var openid = wx.getStorageSync('openid');
      var order = wx.getStorageSync('order');
      var address_id = wx.getStorageSync('addressId');
      //console.log(order)
      //预下单信息
      wx.request({
        url: Host + 'Order/sure_order',
        data: { openid, order: JSON.stringify(order), address_id },
        method: 'post',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function (res) {
          if (res.data.code == 200) {
            that.setData({
              submission: res.data.sureorder.submission,
              freight: res.data.sureorder.freight,
              totalprice: res.data.sureorder.totalprice,
            })
            wx.setStorageSync('addressId', res.data.sureorder.submission.takeMessage.addressId)
            that.cac();
          } else {
            wx.showToast({
              title: res.data.errmsg,
              icon: 'none',
            })
            setTimeout(function(){
              wx.navigateBack({
                delta: 1    
              })
            },1000)
          }
        },
        complete:function(){
          //获取优惠券
          var totalprice = that.data.totalprice;
          //console.log(order)
          wx.request({
            url: Host + 'Order/choosecoupon',
            data: { openid, order: JSON.stringify(order), totalprice },
            method: 'post',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            success: function (res) {
              if (res.data.code == 200) {
                that.setData({
                  coupon: res.data.coupon
                })
                //console.log(res.data.coupon)
              }
            },
          })
         
        }
      })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})